from common import BaseRequestHandler
import common
import observer
from model import *
import logging


class StoryEventBaseHandler(observer.Observer):
    def _post(self):
        story_id = self.request.get('story_id')
        self.story = Story.get_by_id(int(story_id))
        if self.is_user_allowed():
            self._post_()
        else:
            self.not_allowed_error()

    def is_user_allowed(self):
        logging.info(" kkkkkkkk %s", self.story.contains_current_user())
        return self.story.contains_current_user() and self.story.status != 'Closed'

    def notify_history_event(self, event):
        html = self.generate('history_event.html', {'event': event})
        response = {'event': 'add_history_event',
                    'args': {'id_event':event.key().id(),
                              'html_event': html}
                   }
        self.update(self.json_format(response))
    def get_story_event(self, event):
        html = self.generate('event.html', {'event': event})
        return html

class AssignFormIndex(StoryEventBaseHandler):
    def _post_(self):
        self.assign_member()
        self.update(self.json_format(self.get_response()))
        self.notify_history_event(self.event)

    def assign_member(self):
        member_id = self.request.get('assigned_to')
        member = Member.get_by_id(int(member_id))
        self.event = AssignEvent.create(self.story, member.user, self.story.assigned_to, self.request.get('description'))
        self.story.assigned_to = member.user
        self.story.put()

    def get_response(self):
        response = {'event': 'update_assigned',
                    'args': {'id': self.story.key().id(),
                             'assigned_to': self.story.assigned_to.nickname(),
                             'status':self.story.status}
                   }
        return response

class AssignForm(AssignFormIndex):
    def _post_(self):
        self.assign_member()
        self.update(self.json_format(self.get_response()))
        self.notify_history_event(self.event)
        self.json_response(self.get_response_html())

    def get_response_html(self):
        current_user = self.story.assigned_to == users.get_current_user()
        return {'assigned_to': self.story.assigned_to.nickname(),
                'id': self.story.key().id(),
                'current_user': current_user,
                'status':self.story.status,
                'html': self.get_story_event(self.event)}
                
class StoryBaseHandler(BaseRequestHandler):
    def _post(self):
        story_id = self.request.get('story_id')
        self._story = Story.get_by_id(int(story_id))
        if self.is_user_allowed():
            self._post_()
            self.json_response(self.get_response())
        else:
            response = 'Not allowed!!!'
            self.response.set_status(500)
            self.json_response(response)

    def is_user_allowed(self):
        return self._story.contains_current_user() and self._story.status != 'Closed'

class TimeWorkedFormIndex(StoryEventBaseHandler):
    def _post_(self):
        self.update_time()
        self.update(self.json_format(self.get_response()))
        self.notify_history_event(self.event)

    def update_time(self):
        self.time_worked = StoryTimeWorked()
        self.time_worked.story = self.story
        self.time_worked.time = float(self.request.get('time'))
        self.time_worked.put()
        self.event = TimeEvent.create(self.story, self.time_worked.time, self.request.get('description'))
        self.update(self.json_format(self.get_response()))

    def get_response(self):
        elapsed_time = self.story.elapsed_time()
        response = {'event': 'update_time',
                    'args': {'id': self.story.key().id(),
                             'elapsed_time': elapsed_time,
                             'remaining_time': self.story.estimated_time - elapsed_time,
                             'percentage': self.story.percentage()}
                    }
        return response

class TimeWorkedForm(TimeWorkedFormIndex):
    def _post_(self):
        self.update_time()
        self.update(self.json_format(self.get_response()))
        self.notify_history_event(self.event)
        self.json_response(self.get_response_html())       

    def get_response_html(self):
        elapsed_time = self.story.elapsed_time()
        return {    'elapsed_time': elapsed_time,
                    'remaining_time': self.story.estimated_time - elapsed_time,
                    'percentage': self.story.percentage(),
                    'html': self.get_story_event(self.event)}        

class ChangeStoryStatusIndex(StoryEventBaseHandler):
    def _post_(self):
        self.update_status()
        self.update(self.json_format(self.get_response()))
        self.notify_history_event(self.event)

    def update_status(self):
        new_status = self.request.get('status')
        old_status = self.story.status
        self.story.status = new_status
        self.story.put()
        self.event = ResolveEvent.create(self.story, new_status, old_status,
                            self.request.get('description'))

    def get_response(self):
        response = {'event': 'change_status_m',
                    'args': {'id': self.story.key().id(),
                             'status':self.story.status}
                    }
        return response

class ChangeStoryStatus(ChangeStoryStatusIndex):
    def _post_(self):
        self.update_status()
        self.update(self.json_format(self.get_response()))
        self.notify_history_event(self.event)
        self.json_response(self.get_response_html())

    def get_response_html(self):
        return {'status':self.story.status,
                'html': self.get_story_event(self.event)}


class ReopenStory(StoryBaseHandler):
    def _post_(self):
        new_status = 'Active'
        old_status = self._story.status
        self._story.status = new_status
        self._story.put()
        self.event = ResolveEvent.create(self._story, new_status, old_status,
                            self.request.get('description'))
    def is_user_allowed(self):
        return self._story.contains_current_user()
    def get_response(self):
        html = None
        if self.request.get('html') != 'False':
            html = self.generate('event.html', {'event': self.event})
        return {'status':self._story.status, 'html': html}


class PostponeStoryHandler(StoryBaseHandler):
    def _post_(self):
        backlog = self.request.get('backlog')
        self.backlog_ = StoryContainer.get(backlog)
        self.event = MoveEvent.create(self._story, self._story.story_container, self.backlog_,
                         self.request.get('description'))
        self._story.story_container = self.backlog_
        self._story.put()
        
    def get_response(self):
        html = None
        if self.request.get('html') != 'False':
            html = self.generate('event.html', {'event': self.event})
        return {'name': self.backlog_.name, 'id': self.backlog_.key().id(), 'html': html}

class EditStoryDescription(StoryEventBaseHandler):
    def _post_(self):
        self.edit_description()
        self.notify_history_event(self.event)
        self.json_response(self.get_response_html())

    def edit_description(self):
        description = self.request.get('description')
        self.event = EditDescEvent.create(self.story, self.story.description, description)
        self.story.description = description
        self.story.put()

    def get_response_html(self):
        return {'description': self.story.description, 
                'html': self.get_story_event(self.event)}

class CommentStoryIndex(StoryEventBaseHandler):
    def _post_(self):
        self.comment()
        self.notify_history_event(self.event)

    def comment(self):
        comment = self.request.get('comment')
        self.event = CommentEvent.create(self.story, comment)

    def is_user_allowed(self):
        return self.story.status != 'Closed'

class CommentStory(CommentStoryIndex):
    def _post_(self):
        self.comment()
        self.notify_history_event(self.event)
        self.json_response(self.get_response_html())

    def get_response_html(self):
        return {'status':self.story.status,
                'html': self.get_story_event(self.event)}